package org.room402.chat.process;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import org.reactivestreams.Publisher;
import org.room402.constant.chat.MessageAction;
import org.room402.entity.chat.MessageEvent;
import org.room402.entity.chat.UserSession;
import org.room402.framework.chat.container.UserSessionContext;
import org.room402.utile.chat.FastChatUtil;
import org.springframework.stereotype.Component;
import org.springframework.web.reactive.socket.WebSocketSession;
import reactor.core.publisher.Mono;

import java.util.Objects;

@Component
@RequiredArgsConstructor
public class RegisterEventProcess implements MessageProcess {

    private final UserSessionContext userSessionContext;


    @Override
    public boolean actionMatch(MessageEvent event, WebSocketSession session) {

        return MessageAction.register.equals(event.getAction());
    }

    @Override
    public boolean rejectMatch(MessageEvent event, WebSocketSession session) {
        return Objects.nonNull(userSessionContext.getBySid(session.getId()));
    }

    @Override
    public Publisher<Void> process(MessageEvent event, WebSocketSession session) {
        UserSession register = userSessionContext.register(session, JSONUtil.parseObj(event.getContent()));
        MessageEvent messageEvent = MessageEvent.form(null, register.getId(), MessageAction.register_ack, register.getId());
        return session.send(Mono.just(session.textMessage(JSONUtil.toJsonStr(messageEvent))));
    }

    @Override
    public Publisher<Void> reject(MessageEvent event, WebSocketSession session) {
        UserSession userSession = userSessionContext.validBySid(session.getId());
        return FastChatUtil.reject(userSession, "您已经登陆过了，请勿重复登录");
    }
}
